import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
// 页面setup设置名称
import VueSetupExtend from "vite-plugin-vue-setup-extend";
// 自动导入、组件按需引入
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
// 自动化路由
import Pages from "vite-plugin-pages";
// gzip压缩
import viteCompression from "vite-plugin-compression";
// 视图分析工具
import { visualizer } from 'rollup-plugin-visualizer';
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, "");
  // console.log(env);

  return {
    base: mode !== "development" ? "./" : "/",
    plugins: [
      vue(),
      visualizer({
        emitFile: false,
        filename: 'chart.html', // 分析图生成的文件名
        open:true // 如果存在本地服务端口，将在打包后自动展示
      }),
      VueSetupExtend(),
      AutoImport({
        // dts: 'src/auto-import.d.ts',    // 路径下自动生成文件夹存放全局指令
        // imports: ["vue", "vue-router"],
        // dirs: ["src/components"],
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        // dts: 'src/components.d.ts',
        // dirs: ["src/components"],
        deep: false,
        resolvers: [ElementPlusResolver()],
      }),
      Pages({
        dirs: [{ dir: "src/views", baseRoute: "" }],
        exclude: ["**/components/*.vue", "**/components/**/*.vue"], // 排除在外的目录，即不将所有 components 目录下的 .vue 文件生成路由
        importMode: "async",
      }),
      viteCompression(),
    ],
    css: {
      devSourcemap: true,
    },
    build: {
      outDir: "dist",
      minify: "terser", // 设置terserOptions项才生效
      terserOptions: {
        compress: {
          drop_console: mode !== "development" ? true : false,
          drop_debugger: mode !== "development" ? true : false,
        },
      },
      rollupOptions: {
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]",
          manualChunks(id) { // 静态资源分拆打包
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          }
        },
      },
      sourcemap: true,
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
      },
    },
    server: {
      host: true,
      hmr: {
        overlay: true,
        // 解决热更新不同步的问题
        port: 443,
      },
      port: 9999,
      proxy: {
        // [env.VITE_BASE_API]: {
        //   target: env.VITE_BASE_URL,
        //   changeOrigin: true,
        //   rewrite: (path) => path.replace(/^\/api/, ""),
        // },
      },
    },
  };
});
